from PIL import Image, ImageSequence
import os
import sys

def rgb888_to_rgb565(r, g, b):
    """
    将 RGB888 转换为 RGB565 格式
    """
    return ((r & 0xF8) << 8) | ((g & 0xFC) << 3) | (b >> 3)

def save_frame_as_rgb565(frame: Image.Image, index: int, output_dir: str, resize_to: tuple):
    """
    保存单帧为 RGB565 格式的二进制文件
    """
    frame = frame.convert("RGB").resize(resize_to)
    data = bytearray()

    for y in range(frame.height):
        for x in range(frame.width):
            r, g, b = frame.getpixel((x, y))
            rgb565 = rgb888_to_rgb565(r, g, b)
            data += rgb565.to_bytes(2, byteorder='big')  # 大端格式

    filename = os.path.join(output_dir, f"{index:03d}.bin")
    with open(filename, "wb") as f:
        f.write(data)

def gif_to_rgb565_bin(gif_path, output_dir, resize_to):
    """
    将 GIF 转换为 RGB565 格式的二进制文件
    """
    os.makedirs(output_dir, exist_ok=True)
    with Image.open(gif_path) as im:
        index = 0
        for frame in ImageSequence.Iterator(im):
            save_frame_as_rgb565(frame, index, output_dir, resize_to)
            print(f"Saved frame {index}")
            index += 1
    print("✅ 所有帧已转换完成")

if __name__ == "__main__":
    if len(sys.argv) != 4:
        print("Usage: python gif_to_rgb565.py <gif_path> <output_dir> <width,height>")
        sys.exit(1)

    gif_path = sys.argv[1]
    output_dir = sys.argv[2]
    try:
        resize_to = tuple(map(int, sys.argv[3].split(',')))
    except ValueError:
        print("Error: <width,height> must be two integers separated by a comma.")
        sys.exit(1)

    gif_to_rgb565_bin(gif_path, output_dir, resize_to)
